package com.lanswon.qzsmk.controller.cardManageController;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.CardContants;
import com.lanswon.qzsmk.base.DwzPage;
import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.service.cardManageService.ApplyCardService;
import com.lanswon.qzsmk.service.cardManageService.BanckCardBusinessService;
import com.lanswon.qzsmk.service.cardManageService.MakeCardService;
import com.lanswon.qzsmk.service.systemManageService.ParamManageService;
import com.lanswon.qzsmk.vo.MakeCardParamVo;
import com.lanswon.qzsmk.vo.MakeCardQueryConditionVo;
import com.lanswon.qzsmk.vo.MakeCardQueryResultVo;

/**
 * 预制卡(空白卡)任务Controller
 * @author guyawei
 *`
 */
@Controller
@RequestMapping(value="makeCardBlank")
public class MakeCardBlankController  {

	@Autowired
	ApplyCardService acs;
	
	@Autowired
	ParamManageService pm;
	
	@Autowired
	MakeCardService mcs;
	
	@Autowired
	BanckCardBusinessService bbs;

	
	private static Logger logger = (Logger) LoggerFactory.getLogger(MakeCardBlankController.class);

	/**
	 * 跳转空白卡制卡查询页面
	 * @return
	 */
	@RequiresPermissions("makeCardBlank:index")
	@RequestMapping(value="/single",name="空白卡制卡查询页面,makeCardBlank:index",method={RequestMethod.GET,RequestMethod.POST})
	public String makeCardSingle(){
		return "MakeCardSingle";
	}
	
	/**
	 * 查询空白卡的制卡任务
	 * @return
	 */
	@RequiresPermissions("makeCardBlank:getSingleMakeCardInfo")
	@RequestMapping(value="/getSingleMakeCardInfo",name="空白卡制卡任务,makeCardBlank:getSingleMakeCardInfo",method=RequestMethod.POST)
	@ResponseBody
	public DwzPage<MakeCardQueryResultVo> getSingleMakeCardInfo(MakeCardQueryConditionVo mcv,Integer pageNum,Integer numPerPage){
//		System.out.println(mcv+","+pageCount);
		DwzPage<MakeCardQueryResultVo> dPage=null;
//		if(mcv.getNumPerPage()==0){//初次加载页面执行
//			mcv.setCurrentPage(1);
//			mcv.setNumPerPage(20);
//			mcv.setTaskType("2");
//		}else {//分页刷新时执行
//			if(mcv.getCurrentPage()<=1||pageCount==0){
//				mcv.setCurrentPage(1);
//			}else if(mcv.getCurrentPage()>=pageCount&&pageCount!=0){
//				mcv.setCurrentPage(pageCount);
//			}
//			mcv.setTaskType("2");
//		}
		if(pageNum==null&&numPerPage==null){
			pageNum=1;
			numPerPage=20;			
		}
		mcv.setCurrentPage(pageNum);
		mcv.setTaskType(CardContants.TASK_TYPE_NO_NAME_CARD);
		mcv.setNumPerPage(numPerPage);
		mcv.setStartLine((mcv.getCurrentPage()-1)*mcv.getNumPerPage());
		dPage=mcs.queryCardTask(mcv);
		return dPage;
	}
	

	
	/**
	 * 去空白卡制卡任务修改页面
	 * @param request
	 * @return
	 * @throws ApplicationException 
	 */
	@RequiresPermissions("makeCardBlank:goUpdateMakeCardTask")
	@RequestMapping(value="/goUpdateMakeCardTask",name="空白卡制卡任务修改页面,makeCardBlank:goUpdateMakeCardTask",method=RequestMethod.GET)
	public String updateTask( String param,HttpServletRequest request) throws ApplicationException{
		//update
		System.out.println(param);
		MakeCardParamVo mcpv= mcs.queryCardTaskByTaskNo(param);
		request.getSession().setAttribute("sign", false);
		request.getSession().setAttribute("mcpv", mcpv);
		return "AddMakeCardTask";
	}
//	/**
//	 * 获取要修改的信息
//	 * @param 
//	 * @return
//	 */
//	@RequiresPermissions("makeCardBlank:getUpdateInfo")
//	@RequestMapping(value="/getUpdateInfo",name="空白卡制卡获取要修改的信息,makeCardBlank:getUpdateInfo",method=RequestMethod.GET)
//	@ResponseBody
//	public Map<String, Object> getUpdateInfo(HttpServletRequest request){
//		Map<String, Object> map=new HashMap<>();
//		map.put("sign", request.getSession().getAttribute("sign"));
//		map.put("mcpv", request.getSession().getAttribute("mcpv"));
//		request.getSession().removeAttribute("sign");
//		request.getSession().removeAttribute("mcpv");
//		return map;
//	}
	/**
	 * 新增/修改不记名制卡任务，并刷新页面
	 * @return
	 * @throws Exception 
	 */
	@RequiresPermissions("makeCardBlank:addTaskSingle")
	@RequestMapping(value="/addTaskSingle",name="空白卡制卡修改任务,makeCardBlank:addTaskSingle",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> goExportTaskSingle(MakeCardParamVo mcpv ,String count1) throws Exception{
		Map<String,Object> map=new HashMap<String,Object>();
		System.out.println("生成不记名制卡任务+"+mcpv+"$$$"+count1);
		mcpv.setCount(Integer.valueOf(count1));
		mcs.modifyCardTaskByTaskNo(mcpv);
		map.put("statusCode", "200");
		map.put("message", "操作成功");
		map.put("navTabId", "makeCardSingle");
		map.put("callbackType", "closeCurrent");
		map.put("forwardUrl", "makeCardBlank/single");//post请求	
		return map;
	}
	/**
	 * 删除任务
	 * @param mcv
	 * @param pageCount
	 * @param parm
	 * @return
	 */
	@RequiresPermissions("makeCardBlank:deleteSingleTask")
	@RequestMapping(value="/deleteSingleTask",name="空白卡制卡删除任务,makeCardBlank:deleteSingleTask",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> deleteSingleTask(String parm){
		System.out.println(parm);
		String[] taskNo=parm.split(",");
		mcs.deleteCardTasks(taskNo);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("statusCode", "200");
		map.put("message", "任务删除成功");
		return map;
	}
	
	 public static String[] getArray(String [] array){
		 String [] newArray=new String[array.length-1];
		 for(int i=1;i<array.length;i++){
			 newArray[i-1]=array[i];
		 }
		 return newArray;
	 }
	
	/**
	 * 空白卡制卡任务导出页面
	 * @return
	 * @throws ParseException 
	 * @throws ApplicationException 
	 */
	@RequiresPermissions("makeCardBlank:exportTaskSingle")
	@RequestMapping(value="/exportTaskSingle",name="空白卡制卡任务导出,makeCardBlank:exportTaskSingle",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> singleExport(String[]array,HttpServletRequest request,HttpServletResponse response) throws ParseException, ApplicationException{
		System.out.println("导出不记名制卡任务%……%%……%……%……%"+array.length);
		Map<String,Object> map=new HashMap<String,Object>();
		List<MakeCardQueryResultVo> list=new ArrayList<MakeCardQueryResultVo>();
		for(int i=0;i<array.length;i++){
			MakeCardQueryResultVo mcrvo=new MakeCardQueryResultVo();
			String item=array[i];
			mcrvo.setPropertiesBySingleTasked(item.split("#"));
			System.out.println(mcrvo);
			list.add(mcrvo);
			if(i>=1){
				if(!list.get(i).getCardPName().equals(list.get(i-1).getCardPName())){
					map.put("statusCode", "300");
					map.put("message", "卡产品不一致");
					return map;
				}
				if(!list.get(i).getCardPhysicsTypeName().equals(list.get(i-1).getCardPhysicsTypeName())){
					map.put("statusCode", "300");
					map.put("message", "卡物理类型不一致");
					return map;
				}
			}
			
		}
		List<String>ls=null;
		String root = request.getSession().getServletContext().getRealPath("/");
		root+="|"+request.getSession().getServletContext().getContextPath();
		if(list.get(0).getCardPName().contains("银行")){
			ls=bbs.exportBankMakeCardFile(root,list);
			
		}else {	
			ls = mcs.exportMakeCardFile1(root,list);
		}
		logger.debug("下载的文件数量【{}】",ls.size());	
		map.put("paths", ls);
		map.put("statusCode", "200");
		map.put("message", "导出任务成功,路径"+ls);
		
		return map;
	}
	
	/**
	 * 未用：下载
	 * 浏览器如能识别下载文件，使用此方法 
	 * 如不识别 直接location.href
	 */
	@RequiresPermissions("makeCardBlank:download")
	@RequestMapping(value="/download/bjm",name="下载空白卡制卡文件,makeCardBlank:download",method=RequestMethod.POST)
    public void download( String fileName,HttpServletRequest request,HttpServletResponse response){
		String root = request.getSession().getServletContext().getRealPath("/");
		String path = root + PathContants.PROJECT_PATH_DOWNLOAD_MAKECARDFILE_SR +File.separator+fileName;
		logger.debug("文件funck【{}】",fileName);
		logger.debug("下载的路径【{}】",path);
        File f = new File(path);
        response.reset();// 不加这一句的话会出现下载错误 
        response.setHeader("Content-Disposition", "attachment; filename="+fileName);// 设定输出文件头   
        response.setContentType("application/x-msdownload");
        try {
            ServletOutputStream out =  response.getOutputStream();
			
            
            FileInputStream fis =new java.io.FileInputStream(f);
			
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096);
            
            byte[] cache = new byte[4096];
            for (int offset = fis.read(cache); offset != -1; offset = fis.read(cache)) {
                    byteOutputStream.write(cache, 0, offset);
            }
            byte[] bt = null;
            bt = byteOutputStream.toByteArray();               
           
				out.write(bt);
			
            out.flush();
            out.close();
            fis.close();
                      
            } catch (IOException e) {
            	e.printStackTrace();
            	
            	String msg="系统IO流异常";
    			logger.error(msg);
    			throw new SystemException(SystemException.IOException, msg);

    		}  
			
	}
	
}
